<template>
    <div class="ai-idea-tips">
        <AIWarningTips v-if="tableData.length"></AIWarningTips>
    </div>

    <div class="ai-solution-container">
        <!-- 方案选择下拉框 v-if="tableData.length > 0"-->
        <div v-if="0" class="solution-selector">
            <el-select v-model="selectedSolutionIndex" placeholder="请选择AI解题方案" size="default" @change="resetSteps">
                <el-option v-for="(item, index) in tableData" :key="index" :label="`方案 ${index + 1} (${item.lang})`"
                    :value="index" />
            </el-select>
            <el-button type="primary" size="default" @click="refreshData" class="refresh-btn">
                <el-icon>
                    <Refresh />
                </el-icon> 刷新
            </el-button>
        </div>
        <div v-if="tableData.length > 0">
            <div class="ai-solution-header">
                <h3>{{ question?.name }} - AI解题思路({{ displayedSteps.length }}/{{ totalSteps }})</h3>
            </div>

            <div class="ai-solution-content">
                <div class="steps-container">
                    <div class="step-content" v-for="(step, index) in displayedSteps" :key="index"
                        :class="{ 'active-step': index === displayedSteps.length - 1 }">
                        <div v-html="renderMarkdown(step)"></div>
                    </div>
                </div>

                <div class="step-actions">
                    <el-button v-if="displayedSteps.length < totalSteps" type="primary" size="default" @click="nextStep"
                        class="next-step-btn">
                        下一步 <el-icon>
                            <ArrowRight />
                        </el-icon>
                    </el-button>
                </div>
            </div>
        </div>
        <div v-else class="empty-tips"> <el-empty description="暂无AI生成的解题思路"
                image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" /> </div>
    </div>
</template>

<script lang="ts" setup>
import { ArrowRight, Refresh } from '@element-plus/icons-vue';
import { marked } from 'marked';
import { computed, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { asyncUserSelectacaicontent, jilurizhi } from '../../../api';
import AIWarningTips from '../../../components/AIWarningTips.vue';
import { Storekey } from '../../../interface';
import Studycodemodel from '../../../mysql_interface/studycodemodel';
import { AILogAction, AILogMethod } from '../../../util/data';

const props = defineProps<{
    ID?: number,
    user: Studycodemodel.Iuser,
    question?: Studycodemodel.Iquestion
}>()

watch(() => props.ID, () => { start() })

const router = useRouter()
const store = useStore(Storekey)
const tableData = ref<Studycodemodel.Iacaicontent[]>([])
const selectedSolutionIndex = ref(0)
const displayedSteps = ref<string[]>([])

// 计算属性
const currentSolution = computed(() => {
    return tableData.value[selectedSolutionIndex.value] || null
})

const totalSteps = computed(() => {
    return currentSolution.value?.step?.length || 0
})

// 监听选择的方案变化
watch(selectedSolutionIndex, () => {
    resetSteps()
    recordLog(AILogAction.SWITCH_SOLUTION);
})

async function refreshData() {
    await start()
    // recordLog(LogAction.REFRESH_DATA);
}

function nextStep() {
    if (displayedSteps.value.length < totalSteps.value) {
        const nextStepIndex = displayedSteps.value.length
        const stepContent = currentSolution.value?.step?.[nextStepIndex]
        if (stepContent) {
            displayedSteps.value.push(typeof stepContent === 'string' ? stepContent : JSON.stringify(stepContent, null, 2))
            recordLog(AILogAction.VIEW_STEP, nextStepIndex);
        }
    }
}

function resetSteps() {
    displayedSteps.value = []
    if (currentSolution.value?.step?.length) {
        const firstStep = currentSolution.value.step[0]
        if (firstStep) {
            displayedSteps.value.push(typeof firstStep === 'string' ? firstStep : JSON.stringify(firstStep, null, 2))
        }
    }
}

function renderMarkdown(content: string) {
    // console.log("content", content)
    // 确保内容是字符串
    if (typeof content !== 'string') {
        try {
            content = JSON.stringify(content, null, 2)
        } catch {
            content = String(content)
        }
    }
    return marked.parse(content);
    // 简单处理Markdown渲染
    return content
        // 处理无序列表
        .replace(/^\s*-\s+(.*$)/gm, '<li>$1</li>')
        .replace(/(<li>.*<\/li>)+/g, '<ul>$&</ul>')
        // 处理有序列表
        .replace(/^\s*\d+\.\s+(.*$)/gm, '<li>$1</li>')
        .replace(/(<li>.*<\/li>)+/g, '<ol>$&</ol>')
        // 其他原有处理...
        .replace(/### (.*?)(\n|$)/g, '<h3 class="step-h3">$1</h3>')
        .replace(/## (.*?)(\n|$)/g, '<h2 class="step-h2">$1</h2>')
        .replace(/# (.*?)(\n|$)/g, '<h1 class="step-h1">$1</h1>')
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/`(.*?)`/g, '<code class="inline-code">$1</code>');
}

async function start() {
    try {
        const { rows } = await asyncUserSelectacaicontent({
            questionid: props.ID,
            // result: true, // 暂时全部放开、即使代码全AC不通过也可以查看解题思路
            _limit: 10, _sortable: "DESC"
        })
        tableData.value = rows
        resetSteps()
        if (rows.length > 0) {
            recordLog(AILogAction.INIT_VIEW);
        }
    } catch (error) {
        console.error(error)
    }
}
onMounted(() => { start() })

// 记录日志函数
function recordLog(action: AILogAction, stepIndex: number = 0) {
    const arr: [string, any][] = [];
    // 基础信息
    arr.push(["_method_", AILogMethod.AiSolution]);
    arr.push(["type", "AI"]);
    arr.push(["questionid", props.ID]);
    arr.push(["questionname", props.question?.name]);
    let body: { [key: string]: any } = { action, }
    // 操作信息
    // arr.push(["action", action]);
    // 当前方案
    if (tableData.value.length > 0) {
        const current = tableData.value[selectedSolutionIndex.value];
        // arr.push(["solution_index", selectedSolutionIndex.value + 1]);
        // arr.push(["solution_id", current.ID]);
        // arr.push(["solution_lang", current.lang]);
        body.solution_index = selectedSolutionIndex.value + 1
        body.solution_id = current.ID
        // body.solution_lang = current.lang
    }
    // 步骤
    // if (action === "view_step") {
    // arr.push(["step_index", stepIndex + 1]);
    // arr.push(["total_steps", totalSteps.value]);
    // arr.push(["current_content", currentSolution.value?.step?.[stepIndex]]);
    // }
    body.step_index = stepIndex + 1
    body.total_steps = totalSteps.value
    // body.current_content = currentSolution.value?.step?.[stepIndex]
    arr.push(['body', JSON.stringify(body)])
    // 调用日志接口
    console.log("view AI solution Log:", arr);
    jilurizhi(arr);
}
</script>

<style scoped>
.ai-idea-tips {
    --discuss-padding: 16px;
    text-align: center;
}

.ai-solution-container {
    padding: 0 16px 16px;
    border-radius: 4px;
    /* border: 1px solid #ebeef5; */
    /* margin-bottom: 24px; */
    /* background-color: #f8fafc; */
    min-height: 200px;
}

.solution-selector {
    margin-bottom: 16px;
    display: flex;
    gap: 10px;
    align-items: center;
}

.refresh-btn {
    margin-left: 10px;
}

.ai-solution-header {
    margin-bottom: 16px;
    border-bottom: 1px solid #ebeef5;
    padding-bottom: 8px;
}

.ai-solution-header h3 {
    margin: 0;
    color: #333;
    font-size: 16px;
}

.steps-container {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.step-content {
    padding: 12px;
    background: white;
    border-radius: 4px;
    margin-bottom: 8px;
    transition: all 0.2s ease;
}

.step-content.active-step {
    background-color: #f5f7fa;
    border-left: 3px solid #409EFF;
}

.step-actions {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
    margin-top: 16px;
}

.empty-tips {
    padding: 40px 0;
}

/* Markdown样式 */
.step-content :deep(h1) {
    font-size: 20px;
    color: #303133;
    font-weight: 600;
    margin: 16px 0 8px;
}

.step-content :deep(h2) {
    font-size: 18px;
    color: #409EFF;
    font-weight: 600;
    margin: 14px 0 8px;
}

.step-content :deep(h3) {
    font-size: 16px;
    color: #67C23A;
    font-weight: 600;
    margin: 12px 0 8px;
    border-bottom: 1px solid #ebeef5;
    padding-bottom: 4px;
}

.step-content :deep(p) {
    margin: 8px 0;
    line-height: 1.6;
    color: #606266;
}

.step-content :deep(ul) {
    margin: 8px 0;
    padding-left: 24px;
}

.step-content :deep(li) {
    margin: 6px 0;
    line-height: 1.6;
}

.step-content :deep(.inline-code) {
    font-family: 'Courier New', monospace;
    background: #f5f7fa;
    padding: 2px 4px;
    border-radius: 4px;
    color: #e96900;
}
</style>